import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, getCurrentUser } from '@/api/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userId = ref(null)
  const username = ref('')
  const role = ref(null)

  // 登录
  const login = async (loginForm) => {
    try {
      const res = await loginApi(loginForm)
      if (res.code === 200) {
        token.value = res.data.token
        userId.value = res.data.userId
        username.value = res.data.username
        role.value = res.data.role
        
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userId', res.data.userId)
        localStorage.setItem('username', res.data.username)
        localStorage.setItem('role', res.data.role)
        
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(res.message || '登录失败')
        return false
      }
    } catch (error) {
      ElMessage.error('登录失败：' + error.message)
      return false
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userId.value = null
    username.value = ''
    role.value = null
    
    localStorage.clear()
    ElMessage.success('已退出登录')
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await getCurrentUser()
      if (res.code === 200) {
        userId.value = res.data.id
        username.value = res.data.username
        role.value = res.data.role
      }
    } catch (error) {
      console.error('获取用户信息失败', error)
    }
  }

  // 初始化（从localStorage恢复）
  const init = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserId = localStorage.getItem('userId')
    const storedUsername = localStorage.getItem('username')
    const storedRole = localStorage.getItem('role')
    
    if (storedToken) {
      token.value = storedToken
      userId.value = storedUserId
      username.value = storedUsername
      role.value = parseInt(storedRole)
    }
  }

  init()

  return {
    token,
    userId,
    username,
    role,
    login,
    logout,
    getUserInfo
  }
})

